﻿using System.Collections.ObjectModel;
using System.IO;
using Agnes.Core;
using System.Xml.Linq;
using Caliburn.Micro;
using System;
using System.Collections.Generic;

namespace Agnes.MyDocsLib
{
    /// <summary>
    /// 文章管理器
    /// </summary>
    public class ArticleManager : PropertyChangedBase
    {
        #region 私有成员

        private string _documentBasePath; // 文档存放的基路径
        private string _articlesXml; // 文档Xml文件地址

        #endregion

        #region 属性

        private ObservableCollection<Catalog> _roots; 
        /// <summary>
        /// 文章树的根节点
        /// </summary>
        public ObservableCollection<Catalog> Roots
        {
            get { return _roots; }
            private set
            {
                _roots = value;
                NotifyOfPropertyChange(() => Roots);
            }
        }

        private IArticleNode _selectedNode;
        /// <summary>
        /// 选择的文章树的节点
        /// </summary>
        public IArticleNode SelectedNode 
        {
            get
            {
                return _selectedNode;
            }
            set
            {
                _selectedNode = value;
                NotifyOfPropertyChange(() => SelectedNode);
            }
        }

        private ObservableCollection<string> _labels;
        /// <summary>
        /// 标签集合
        /// </summary>
        public ObservableCollection<string> Labels
        {
            get
            {
                return _labels;
            }
            set
            {
                _labels = value;
                NotifyOfPropertyChange(() => Labels);
            }
        }

        #endregion

        #region 公开方法

        public ArticleManager()
        {
            AgnesServiceManager.AgnesSlnService.SlnClosedHandler
                += (sender, args) =>
                       {
                           Save();
                           Roots.Clear();
                       };
            AgnesServiceManager.AgnesSlnService.SlnOpenedHanlder
                += (sender, args) => Load();
        }

        /// <summary>
        /// 加载文章树
        /// </summary>
        public void Load()
        {
            try
            {
                AgnesServiceManager.LogServ.Info("MyDocsLib--加载文章树...");
                if (AgnesServiceManager.AgnesSlnService.CurrentSln == null)
                {
                    AgnesServiceManager.LogServ.Error("MyDocsLib--尝试加载文章树失败：未打开解决方案！");
                    return;
                }

                _documentBasePath = Path.Combine(AgnesServiceManager.AgnesSlnService.CurrentSln.TempDir, "Date_MyDocsLib");
                _articlesXml = Path.Combine(_documentBasePath, "Articles.xml");

                Roots = new ObservableCollection<Catalog>();
                Labels = new ObservableCollection<string>();
                if (File.Exists(_articlesXml))
                {
                    XElement el = XElement.Load(_articlesXml);
                    foreach (XElement i in el.Elements("Catalog"))
                    {
                        Roots.Add(Catalog.FetchAsChild(i));
                    }
                }
            }
            catch (Exception ex)
            {
                AgnesServiceManager.LogServ.Error("MyDocsLib--加载文章库，错误：" + ex.Message);
            }
        }

        /// <summary>
        /// 保存文章树
        /// </summary>
        public void Save()
        {
            try
            {
                 if (AgnesServiceManager.AgnesSlnService.CurrentSln == null || Roots == null)
                {
                    return;
                }
                AgnesServiceManager.LogServ.Info("MyDocsLib--保存文章树...");
                if (!Directory.Exists(_documentBasePath))
                {
                    Directory.CreateDirectory(_documentBasePath);
                }
                if (!File.Exists(_articlesXml))
                {
                    File.Create(_articlesXml).Close();
                }
                XElement el = new XElement("Articles");
                foreach (Catalog i in Roots)
                {
                    i.SaveToXml(el.Add);
                }
                el.Save(_articlesXml);
            }
            catch (Exception ex)
            {
                AgnesServiceManager.LogServ.Error("MyDocsLib--保存文章库失败，错误：" + ex.Message);
            }
        }

        /// <summary>
        /// 删除目录
        /// </summary>
        /// <param name="catalog"></param>
        public void DelCatalog(Catalog catalog)
        {
            if (catalog.ParentCatalog != null)
            {
                catalog.Delete();
            }
            else
            {
                Roots.Remove(catalog);
            }
        }

        /// <summary>
        /// 删除文章
        /// </summary>
        /// <param name="article"></param>
        public void DelArticle(Article article)
        {
            if (File.Exists(article.DocumentPath))
            {
                File.Delete(article.DocumentPath);
            }

            article.ParentCatalog.Childs.Remove(article);
        }

        public List<Article> GetArticels(string label)
        {
            List<Article> articles = new List<Article>();
            foreach (Catalog i in Roots)
            {
                articles.AddRange(GetArticels(i, label));
            }

            return articles;
        }

        private List<Article> GetArticels(Catalog catalog, string label)
        {
            List<Article> articles = new List<Article>();
            foreach (IArticleNode i in catalog.Childs)
            {
                if (i is Catalog)
                {
                    articles.AddRange(GetArticels(i as Catalog, label));
                }
                else
                {
                    if ((i as Article).Labels.IndexOf(label) != -1)
                    {
                        articles.Add(i as Article);
                    }
                }
            }

            return articles;
        }

        #endregion
    }

}
